﻿using System;
using System.Configuration;
using System.Data;
using System.Data.Common;
using MySql.Data.MySqlClient;
using WFC.DAL.Interfaces.StatementSources;

namespace WFC.DAL.PersistentStorage
{
    internal static class DbManager
    {

        private const string DfltConn = "WFCData";
        private static string ConnectionString { get; set; }

        internal static DataSet ExecuteStatement(IStatementSource statementSource)
        {
            ConnectionString = ConfigurationManager.ConnectionStrings[DfltConn].ConnectionString;
            MySqlCommand command = statementSource.Command;
            var dataSet = new DataSet();

            using (var connection = new MySqlConnection(ConnectionString))
            {
                connection.Open();
                command.Connection = connection;

                var dataAdapter = new MySqlDataAdapter(command);
                dataAdapter.Fill(dataSet);
            }

            return dataSet;
        }

        internal static int ExcuteScalar(IStatementSource statementSource)
        {
            ConnectionString = ConfigurationManager.ConnectionStrings[DfltConn].ConnectionString;
            DbCommand command = statementSource.Command;

            int value = 0;
            using (var connection = new MySqlConnection(ConnectionString))
            {
                connection.Open();
                command.Connection = connection;

                value = Convert.ToInt32(command.ExecuteScalar());
            }

            return value;
        }

        internal static int ExecuteNonQuery(IStatementSource statementSource)
        {
            ConnectionString = ConfigurationManager.ConnectionStrings[DfltConn].ConnectionString;
            DbCommand command = statementSource.Command;

            int value = 0;
            using (var connection = new MySqlConnection(ConnectionString))
            {
                connection.Open();
                command.Connection = connection;

                value = command.ExecuteNonQuery();
            }

            return value;
        }

        internal static DbDataReader ExecuteReader(IStatementSource statementSource)
        {
            ConnectionString = ConfigurationManager.ConnectionStrings[DfltConn].ConnectionString;
            DbCommand command = statementSource.Command;

            var connection = new MySqlConnection(ConnectionString);
            connection.Open();

            command.Connection = connection;
            return command.ExecuteReader(CommandBehavior.CloseConnection);
        }

    }
}
